package com.nbgroup.service.user;


import com.nbgroup.dao.RoleUserRepositoty;
import com.nbgroup.dao.UserDao;
import com.nbgroup.dao.role.RoleDao;
import com.nbgroup.entity.Role;
import com.nbgroup.entity.RoleUser;
import com.nbgroup.entity.User;
import com.nbgroup.utils.TimeTools;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.*;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Hanh on 2018/8/16 0016.
 * 用户信息处理逻辑层
 */
@Service
@Transactional
public class UsersService {
    @Autowired
    UserDao userserDao;
    @Autowired
    RoleDao roleDao;
    @Autowired
    RoleUserRepositoty roleUserRepositoty;
    //获取分页
    public Page<User> findByPage(final User user, Integer page, Integer pageSize) throws Exception {
        if (null == page || "".equals(page) || "0".equals(page)) {//排空，设置默认值
            page = 1;
        }
        if (null == pageSize || "".equals(pageSize) || "0".equals(pageSize)) {//排空，设置默认值
            pageSize = 10;
        }
        final Sort sort = new Sort(Sort.Direction.DESC, "createtime");//使用jpa的排序工具,按照事件创建时间倒序
        PageRequest pageRequest = new PageRequest(--page, pageSize, sort);//使用jpa的分页工具
        return userserDao.findAll(new Specification<User>() {
            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList();
//                Join<Role, Emp> empJoin = root.join("empList", JoinType.LEFT);
                predicates.add(cb.equal(root.get("sts"), 1));//查询可用
                if (StringUtils.isNotBlank(user.getUsername())) {//按照用户名称
                    Path<String> namePath = root.get("username");
                    predicates.add(cb.like(namePath, "%" + user.getUsername() + "%"));
                }
//                if (StringUtils.isNotBlank(cgAttendance.getPrincipal())) {//按照出勤组名称
//                    Path<String> namePath = root.get("principal");
//                    predicates.add(cb.like(namePath, "%" + cgAttendance.getPrincipal() + "%"));
//                }
//                if (StringUtils.isNotBlank(cgAttendance.getEmpList())) {//按照出勤组名称
//                    Path<String> namePath = root.get("empList");
//                    predicates.add(cb.like(namePath, "%" + cgAttendance.getEmpList() + "%"));
//                }
//                if (StringUtils.isNotBlank(TimeTools.CheckString(cgAttendance.getStartTime()).toString())) {//大于或等于传入时间
//                    predicates.add(cb.greaterThanOrEqualTo(root.get("startTime").as(String.class), cgAttendance.getStartTime().toString()));
//                }
//                if (StringUtils.isNotBlank(TimeTools.CheckString(cgAttendance.getEndTime()).toString())) {//小于或等于传入时间
//                    predicates.add(cb.lessThanOrEqualTo(root.get("endTime").as(String.class), cgAttendance.getEndTime().toString()));
//                }
                query.where(predicates.toArray(new Predicate[predicates.size()]));
                return null;
            }
        }, pageRequest);//进行分页
    }
    //根据id查询数据
    public User getInfoById(String id){
        return userserDao.findOne(Long.parseLong(id));
    }
    //添加
    public String save(User user){
        user.setCreatetime(TimeTools.getTimeSec());
        user.setSts("1");
        if(user.getUsername()!=null&&!user.getUsername().equals("")&&user.getPassword()!=null&&!user.getPassword().equals("")){
            try{
                User userBySelect = this.findUserByName(user.getUsername());
                //检查可用用户中用户名是否重复
                if(userBySelect==null||userBySelect.getId().equals("")){
                    //添加角色
                    List<Role> roles = new ArrayList<Role>();
                    roles.add(roleDao.findOne(Long.parseLong("1")));
                    user.setAuthorities(roles);
                    User save = userserDao.save(user);
                    String roleId = user.getRoleId();
                    RoleUser r =new RoleUser();
                    r.setRoleId(Long.parseLong(roleId));
                    r.setUserId(save.getId());
                    roleUserRepositoty.save(r);
                }else{
                    return "添加失败，用户名重复！";
                }
            }catch (Exception e){
                e.printStackTrace();
                return "添加失败，请联系管理员！";
            }
        }else{
            return "数据错误，请填写正确数据！";
        }
        return "添加成功";
    }
    //修改
    public String update(User user){

//        if(user.getUsername()!=null&&!user.getUsername().equals("")&&user.getPassword()!=null&&!user.getPassword().equals("")){
            try{
                User olduser = userserDao.findOne(user.getId());
                olduser.setPassword(user.getPassword());
                olduser.setCreatetime(TimeTools.getTimeSec());
                olduser.setSts("1");
//                //检查可用用户中用户名是否重复
//                if(this.findUserByName(user.getUsername())==null||this.findUserByName(user.getUsername()).getId().equals(user.getId())){
                User user1 = userserDao.saveAndFlush(olduser);
                String roleId = user.getRoleId();
                RoleUser userId = roleUserRepositoty.findByUserId(user1.getId());
                userId.setRoleId(Long.parseLong(roleId));
                roleUserRepositoty.saveAndFlush(userId);
//                }else{
//                    return "修改失败，用户名重复！";
//                }
            }catch (Exception e){
                e.printStackTrace();
                return "修改失败，请联系管理员！！！";
            }
//        }else{
//            return "数据错误，请填写正确数据！";
//        }
        return "修改成功";
    }

    //删除
    public String delete(String id){
        User user = userserDao.findOne(Long.parseLong(id));
        try {
            if(!user.getUsername().equals("admin")){
                user.setSts("0");
                userserDao.saveAndFlush(user);
            }else{
                return "删除失败，不能删除admin！！！";
            }

        }catch (Exception e){
            return "删除失败，请联系管理员！！！";
        }
        return "删除成功！";
    }
    //重置密码
    public String reset(String id){
        User user = userserDao.findOne(Long.parseLong(id));
        try {
            if(!user.getUsername().equals("admin")){
                user.setPassword("123456");
                userserDao.saveAndFlush(user);
            }else{
                return "重置失败，不能重置admin！！！";
            }

        }catch (Exception e){
            return "重置失败，请联系管理员！！！";
        }
        return "重置成功！";
    }
    //根据用户名查询可用用户数量
    public User findUserByName(String username){
        User user = userserDao.findByUsernameAndSts(username,"1");
        return user;
    }
}
